import {Component, OnInit} from '@angular/core';
import {BladeContainerInterface} from '../../../../shared/blade/blade-container.interface';
import {Blade} from '../../../../shared/blade/blade.model';
import {Observable} from 'rxjs/Observable';
import {FormBuilder, FormGroup, Validators, FormControl} from '@angular/forms';
import {Factory} from '../../../../entity/factory.model';
import {Command} from '../../../../shared/toolbar.service';
import {TurbStatusService} from '../../../../service/turbstatus.service';
import {BladeContainerBase} from '../../../../shared/blade/blade-container-base';
import {FactoryService} from '../../../../service/factory.service';

@Component({
  selector: 'app-factory-edit',
  templateUrl: './factory-edit.component.html',
  styleUrls: ['./factory-edit.component.css']
})
export class FactoryEditComponent extends BladeContainerBase<Factory> {
  file: File;
  baseUrl: string;

  constructor(
    private factoryService: FactoryService,
    private fb: FormBuilder,
  ) {
    super(fb)
  }

  ngOnInit() {
    this.baseUrl = window.location.origin;
    this.baseUrl = this.baseUrl == 'http://localhost:4200' ? 'http://192.168.15.109:8080' : this.baseUrl;
    //编辑时注册按钮和按钮命令
    if (!this.isNew) {
      this.commands = [
        new Command('save', '保存', 'fa fa-save', 'setofkey:update', (blade) => this.exeSaveChange(blade), (blade) => this.canSaveChange(blade)),
        new Command('reset', '重置', 'fa fa-save', 'setofkey:reset', (blade) => this.exeReset(blade), (blade) => this.canReset(blade)),
      ]
    }
    else {
      this.currentEntity = new Factory(0, '', '');
    }
    super.ngOnInit();
  }

  /**
   * 初始化数据
   *
   *
   * @memberof TurbstatusValueListComponent
   */
  initData(): any | Observable<any> | Promise<any> {
    this.formPatchValue(this.currentEntity);

  }

  exeSaveChange(blade: any): void {
    this.saveChange();
  }

  canSaveChange(blade: any): boolean {
    return this.hasChange() && !this.hasError();
  }

  exeReset(blade: any): void {
    this.file = null
    return this.formGroup.reset(this.currentEntity);
  }

  canReset(blade: any): boolean {
    return this.hasChange();
  }

  /**
   * 创建表单
   *
   *
   * @memberof DicKeyEditComponent
   */
  createForm() {
    this.formGroup = this.fromBuider.group({
      // "factoryName": [this.currentEntity.factoryName, [
      //   Validators.required,
      //   Validators.pattern("^[\u4e00-\u9fa5a-zA-Z0-9]+$"),
      //   Validators.maxLength(50),
      // ], (control: FormControl): any => this.factoryNameAsnyValidator(control)
      // ],
      'factoryName': this.currentEntity.factoryName,
      'factoryLogo': this.currentEntity.factoryLogo
    });
  }

  /**
   *异步校验公司名称
   *
   * @param {FormControl} control
   * @returns
   * @memberof FactoryEditComponent
   */
  factoryNameAsnyValidator(control: FormControl) {
    if (!control.value || control.value == this.currentEntity.factoryName) {
      return Observable.of(null);
    }
    return this.factoryService.hasFactoryName(control.value, this.currentEntity.factoryId)
      .map(res => res ? {exist: true} : null);
  }

  /**
   * 设置表单错误对象
   *
   *
   * @memberof BladeContainerBase
   */
  setFormError(): void {
    this.formErrors = {
      'factoryName': '',
    };
  }

  /**
   * 设置表单验证信息
   *
   *
   * @memberof BladeContainerBase
   */
  setValidationMessages(): void {
    this.validationMessages = {
      'factoryName': {
        'required': '状态名称不能为空。',
        'pattern': '状态名称必须是汉字字母数字。',
        'maxlength': '状态名称不能多于50个字符长度。',
        'exist': '状态名称已存在。',
      },

    };
  }

  /**
   * 异步校验status是否存在
   *
   * @param {FormControl} control
   * @returns {Promise<true>}
   *
   * @memberof turbstatusEditComponent
   */
  statusAsnyValidator(control: FormControl, name: string, current: any): any {
    if (!control.value || control.value == current) {
      return Observable.of(null);
    }
    /*  return this.turbastatusService.hasStatusName(control.value, this.currentEntity.factoryId, name)
       .map(res => res ? { exist: true } : null); */
  }

  /**
   * 创建一个风机状态
   *
   *
   * @memberof TurbstatusEditComponent
   */
  onCreate() {
    if (!this.hasError()) {

      if (this.file) {
        this.factoryService.upFile(this.file)
          .then(res => {
            this.changeCurrent(res);
            this.onSaveCreate();
          })
          .catch(err => {
            console.log(err);
          });
      } else {
        this.changeCurrent();
        this.onSaveCreate();
      }

    }
  }

  onSaveCreate() {
    this.factoryService.create(this.currentEntity)
      .then(res => {
        (this.parentBlade.bladeContainerInstance).refresh(res);
        this.bladeService.closeBlade(this.currentBlade);
      })
      .catch(error => this.bladeData.error = error)
      .then(res => this.bladeData.isLoading = false);
  }

  /**
   *
   *
   *
   * @memberof TurbstatusEditComponent
   */
  saveChange(): any | Promise<any> | Observable<any> {

    if (this.canSaveChange(this.currentBlade)) {

      if (this.file) {
        this.factoryService.upFile(this.file)
          .then(res => {
            this.changeCurrent(res);
            this.save()
          })
          .catch(err => {
            console.log(err)
          })
      } else {
        this.changeCurrent();
        this.save()
      }

    }
  }

  save() {
    this.factoryService.update(this.currentEntity)
      .then(res => {
        if (res) {
          (this.parentBlade.bladeContainerInstance).refresh(res);
          this.bladeService.closeBlade(this.currentBlade);
          return true;
        }
      })
      .catch(error => this.bladeData.error = error)
      .then(res => this.bladeData.isLoading = false);
  }

  changeCurrent(url?: string) {
    this.bladeData.isLoading = true;
    let formValue = this.formGroup.value as Factory;
    this.currentEntity.factoryName = formValue.factoryName;
    if (url) {
      this.currentEntity.factoryLogo = url;
    }

  }

  onUpload(ev) {
    this.formGroup.controls['factoryLogo'].setValue(ev.files[0].name);
    this.file = ev.files;

  }

  onRemove(ev) {
    this.formGroup.controls['factoryLogo'].setValue(this.currentEntity.factoryLogo);
    this.file = null;
  }


}


// WEBPACK FOOTER //
// ./src/app/module/basic/factory/factory-edit/factory-edit.component.ts
